package com.dong.zhaofengcontact2018.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.dong.zhaofengcontact2018.BuildConfig;
import com.dong.zhaofengcontact2018.R;
import com.dong.zhaofengcontact2018.database.SqlMethod;
import com.dong.zhaofengcontact2018.model.Folk;

import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class ShowContactPhoneActivity extends AppCompatActivity {
    private String TAG;
    private EditText mPhonesEditText;
    private Spinner mNameSpinner;
    private Spinner mUnitSpinner;
    private Spinner mDeptSpinner;
    private Spinner mRankSpinner;
    private Spinner mOfficeSpinner;
    private Spinner mRoomNumberSpinner;
    private Spinner mInPhonesSpinner;
    private Spinner mOutPhonesSpinner;
    private Spinner mNickNameSpinner;
    private Spinner mAddressSpinner;
    private Spinner mInGroupSpinner;
    private Spinner mLastCallsSpinner;
    private List<Folk> mFolkList;
    private Cursor mFolkCursor;
    private ListView mPhonesListView;
    private TextView mCombineConditionTextView;
    //搜索条件
    private HashMap<String, String> mSearchConditionMap;
    private SqlMethod mSqlMethod;
    //
    private ArrayList<String> mUnitList;
    private ArrayList<String> mDeptList;
    private ArrayList<String> mRankList;
    private ArrayList<String> mOfficeList;
    private ArrayList<String> mRoomNumberList;
    private ArrayList<String> mInPhonesList;
    private ArrayList<String> mOutPhonesList;
    private ArrayList<String> mNickNameList;
    private ArrayList<String> mAddressList;
    private ArrayList<String> mInGroupList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_contact_phone);

        TAG = getPackageName().getClass().getSimpleName();
        // TODO: 2018/8/10 初始化视图
        initView();
        // TODO: 2018/8/10 初始化所需要的数据
        initData();
        // TODO: 2018/8/10  初始化 电话特征数字编辑框
        initPhones(mPhonesEditText);
        // TODO: 2018/8/10  姓名列,取姓氏,并排序,最后添加字母
        initFamilyNameIndex(mNameSpinner);
        // TODO: 2018/8/10 单位 关键词 分类
        initUnit(mUnitSpinner);
        // TODO: 2018/8/10 部门
        initDept(mDeptSpinner);
        // TODO: 2018/8/10 人员之职级
        initRank(mRankSpinner);
        // TODO: 2018/8/10 办公室,工作场所
        initOffice(mOfficeSpinner);
        // TODO: 2018/8/10 门号,如果 办公室有多个房间
        initRoomNumber(mRoomNumberSpinner);
        // TODO: 2018/8/10 内线
        initInPhones(mInPhonesSpinner);
        // TODO: 2018/8/10 外线
        initOutPhones(mOutPhonesSpinner);
        // TODO: 2018/8/10 绰号
        initNickName(mNickNameSpinner);
        // TODO: 2018/8/10 住址
        initAddress(mAddressSpinner);
        // TODO: 2018/8/10 分组
        initInGroup(mInGroupSpinner);
        // TODO: 2018/8/10 热线
        initLastCalls(mLastCallsSpinner);
    }

    // TODO: 2018/8/10 热线
    private void initLastCalls(Spinner lastCallsSpinner) {
        lastCallsSpinner.setVisibility(View.GONE);
        // TODO: 2018/8/10 从电话记录中,查找最近的通话记录,显示5个电话号码
    }


    // TODO: 2018/8/10 分组
    // TODO: 2018/8/28
    private void initInGroup(final Spinner inGroupSpinner) {
        mInGroupList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) inGroupSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mInGroupList.contains(field)) {// 添加时,排除重复
                    mInGroupList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mInGroupList.size() == 0) {
            return;
        }
        inGroupSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mInGroupList.add(0, "- 分组 -");
        inGroupSpinner.setBackgroundColor(Color.WHITE);
        inGroupSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> inGroupAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mInGroupList);
        inGroupSpinner.setAdapter(inGroupAdapter);
        inGroupSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                inGroupSpinner.setSelection(0);
                return true;
            }
        });
        inGroupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) inGroupSpinner.getTag())) {
                        mSearchConditionMap.remove((String) inGroupSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) inGroupSpinner.getTag(), mInGroupList.get(inGroupSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 住址
    private void initAddress(final Spinner addressSpinner) {
        mAddressList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) addressSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mAddressList.contains(field)) {// 添加时,排除重复
                    mAddressList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mAddressList.size() == 0) {
            return;
        }
        addressSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mAddressList.add(0, "- 住址 -");
        addressSpinner.setBackgroundColor(Color.WHITE);
        addressSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        final ArrayAdapter<String> addressAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mAddressList);
        addressSpinner.setAdapter(addressAdapter);
        addressSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                addressSpinner.setSelection(0);
                return true;
            }
        });
        addressSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // TODO: 2018/8/13   要处理
                // TODO: 2018/8/28
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) addressSpinner.getTag())) {
                        mSearchConditionMap.remove((String) addressSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) addressSpinner.getTag(), mAddressList.get(addressSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 绰号
    private void initNickName(final Spinner nickNameSpinner) {
        mNickNameList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) nickNameSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mNickNameList.contains(field)) {// 添加时,排除重复
                    mNickNameList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mNickNameList.size() == 0) {
            return;
        }
        nickNameSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mNickNameList.add(0, "- 绰号 -");
        nickNameSpinner.setBackgroundColor(Color.WHITE);
        nickNameSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> nickNameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mNickNameList);
        nickNameSpinner.setAdapter(nickNameAdapter);
        nickNameSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                nickNameSpinner.setSelection(0);
                return true;
            }
        });
        nickNameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) nickNameSpinner.getTag())) {
                        mSearchConditionMap.remove((String) nickNameSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) nickNameSpinner.getTag(), mNickNameList.get(nickNameSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 外线
    private void initOutPhones(final Spinner outPhonesSpinner) {
        mOutPhonesList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) outPhonesSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mOutPhonesList.contains(field)) {// 添加时,排除重复
                    mOutPhonesList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mOutPhonesList.size() == 0) {
            return;
        }
        outPhonesSpinner.setVisibility(View.VISIBLE);
        Collections.sort(mOutPhonesList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.parseInt(o1) - Integer.parseInt(o2);
            }
        });
        // 最前位置 加一个中文台头
        mOutPhonesList.add(0, "- 外线 -");
        outPhonesSpinner.setBackgroundColor(Color.WHITE);
        outPhonesSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        final ArrayAdapter<String> outPhonesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mOutPhonesList);
        outPhonesSpinner.setAdapter(outPhonesAdapter);
        outPhonesSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                outPhonesSpinner.setSelection(0);
                return true;
            }
        });
        outPhonesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) outPhonesSpinner.getTag())) {
                        mSearchConditionMap.remove((String) outPhonesSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) outPhonesSpinner.getTag(), mOutPhonesList.get(outPhonesSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 内线
    private void initInPhones(final Spinner inPhonesSpinner) {
        mInPhonesList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) inPhonesSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mInPhonesList.contains(field)) {// 添加时,排除重复
                    mInPhonesList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mInPhonesList.size() == 0) {
            return;
        }
        inPhonesSpinner.setVisibility(View.VISIBLE);
        Collections.sort(mInPhonesList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.parseInt(o1) - Integer.parseInt(o2);
            }
        });
        // 最前位置 加一个中文台头
        mInPhonesList.add(0, "- 内线 -");
        inPhonesSpinner.setBackgroundColor(Color.WHITE);
        inPhonesSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> inPhonesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mInPhonesList);
        inPhonesSpinner.setAdapter(inPhonesAdapter);
        inPhonesSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                inPhonesSpinner.setSelection(0);
                return true;
            }
        });
        inPhonesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) inPhonesSpinner.getTag())) {
                        mSearchConditionMap.remove((String) inPhonesSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) inPhonesSpinner.getTag(), mInPhonesList.get(inPhonesSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 门号,如果 办公室有多个房间
    private void initRoomNumber(final Spinner roomNumberSpinner) {
        mRoomNumberList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) roomNumberSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mRoomNumberList.contains(field)) {// 添加时,排除重复
                    mRoomNumberList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mRoomNumberList.size() == 0) {
            return;
        }
        roomNumberSpinner.setVisibility(View.VISIBLE);
        Collections.sort(mRoomNumberList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.parseInt(o1) - Integer.parseInt(o2);
            }
        });
        // 最前位置 加一个中文台头
        mRoomNumberList.add(0, "- 门号 -");
        roomNumberSpinner.setBackgroundColor(Color.WHITE);
        roomNumberSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> roomNumberAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mRoomNumberList);
        roomNumberSpinner.setAdapter(roomNumberAdapter);
        roomNumberSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                roomNumberSpinner.setSelection(0);
                return true;
            }
        });
        roomNumberSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) roomNumberSpinner.getTag())) {
                        mSearchConditionMap.remove((String) roomNumberSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) roomNumberSpinner.getTag(), mRoomNumberList.get(roomNumberSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 办公室,工作场所
    private void initOffice(final Spinner officeSpinner) {
        mOfficeList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) officeSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mOfficeList.contains(field)) {// 添加时,排除重复
                    mOfficeList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mOfficeList.size() == 0) {
            return;
        }
        officeSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mOfficeList.add(0, "- 办公室 -");
        officeSpinner.setBackgroundColor(Color.WHITE);
        officeSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> officeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mOfficeList);
        officeSpinner.setAdapter(officeAdapter);
        officeSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                officeSpinner.setSelection(0);
                return true;
            }
        });
        officeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) officeSpinner.getTag())) {
                        mSearchConditionMap.remove((String) officeSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) officeSpinner.getTag(), mOfficeList.get(officeSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 人员之职级
    private void initRank(final Spinner rankSpinner) {
        mRankList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) rankSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mRankList.contains(field)) {// 添加时,排除重复
                    mRankList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mRankList.size() == 0) {
            return;
        }
        rankSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mRankList.add(0, "- 职级 -");
        rankSpinner.setBackgroundColor(Color.WHITE);
        rankSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> deptAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mRankList);
        rankSpinner.setAdapter(deptAdapter);
        rankSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                rankSpinner.setSelection(0);
                return true;
            }
        });
        rankSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) rankSpinner.getTag())) {
                        mSearchConditionMap.remove((String) rankSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) rankSpinner.getTag(), mRankList.get(rankSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 部门
    private void initDept(final Spinner deptSpinner) {
        mDeptList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) deptSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mDeptList.contains(field)) {// 添加时,排除重复
                    mDeptList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mDeptList.size() == 0) {
            return;
        }
        deptSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mDeptList.add(0, "- 部门 -");
        deptSpinner.setBackgroundColor(Color.WHITE);
        deptSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> deptAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mDeptList);
        deptSpinner.setAdapter(deptAdapter);
        deptSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                deptSpinner.setSelection(0);
                return true;
            }
        });
        deptSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) deptSpinner.getTag())) {
                        mSearchConditionMap.remove((String) deptSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) deptSpinner.getTag(), mDeptList.get(deptSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    // TODO: 2018/8/10 单位 关键词 分类
    // TODO: 2018/8/28
    private void initUnit(final Spinner unitSpinner) {
        mUnitList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) unitSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                if (!mUnitList.contains(field)) {// 添加时,排除重复
                    mUnitList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        if (mUnitList.size() == 0) {
            return;
        }
        unitSpinner.setVisibility(View.VISIBLE);
        // 最前位置 加一个中文台头
        mUnitList.add(0, "- 单位 -");
        unitSpinner.setBackgroundColor(Color.WHITE);
        unitSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        final ArrayAdapter<String> unitAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mUnitList);
        unitSpinner.setAdapter(unitAdapter);
        unitSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                unitSpinner.setSelection(0);
                return true;
            }
        });
        unitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) unitSpinner.getTag())) {
                        mSearchConditionMap.remove((String) unitSpinner.getTag());
                    }
                } else {
                    ((TextView) view).setTextColor(Color.RED);
                    mSearchConditionMap.put((String) unitSpinner.getTag(), mUnitList.get(unitSpinner.getSelectedItemPosition()));
                }
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    // TODO: 2018/8/10  姓名列,取姓氏,并排序,最后添加字母
    // TODO: 2018/8/28  
    private void initFamilyNameIndex(final Spinner nameSpinner) {
        final ArrayList<String> familyNameList = new ArrayList<>();
        mFolkCursor.moveToFirst();
        int columnIndex = mFolkCursor.getColumnIndex((String) nameSpinner.getTag());
        String field;
        do {
            field = mFolkCursor.getString(columnIndex);
            if (field != null && !("".equals(field))) {
                // 如果是姓名列,只取首字
                field = field.substring(0, 1);
                if (!familyNameList.contains(field)) {// 添加时,排除重复
                    familyNameList.add(field);
                }
            }
        } while (mFolkCursor.moveToNext());
        // TODO: 2018/8/8 姓氏 排序
        Collections.sort(familyNameList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (PinyinHelper.toHanyuPinyinStringArray((o1.toCharArray())[0])[0])
                        .compareToIgnoreCase(PinyinHelper.toHanyuPinyinStringArray((o2.toCharArray())[0])[0]);
            }
        });
        // TODO: 2018/8/9 在 排好序的姓名首字之间,插入索引拼音字母
        String lastLetter = "";
        String currentLetter;
        for (int i1 = 0; i1 < familyNameList.size(); i1++) {
            // 大写首字母,单个字母
            currentLetter = (((PinyinHelper.toHanyuPinyinStringArray((familyNameList.get(i1)).toCharArray()[0]))[0])
                    .toUpperCase()).substring(0, 1);
            if (!lastLetter.equals(currentLetter)) {
                familyNameList.add(i1, "      " + currentLetter);
                lastLetter = currentLetter;
            }
        }
        // 最前位置 加一个中文台头
        familyNameList.add(0, "- 姓 -");
        nameSpinner.setBackgroundColor(Color.WHITE);
        nameSpinner.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        ArrayAdapter<String> familyNameAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, familyNameList);
        nameSpinner.setAdapter(familyNameAdapter);
        nameSpinner.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                nameSpinner.setSelection(0);
                return true;
            }
        });
        nameSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    if (mSearchConditionMap.containsKey((String) nameSpinner.getTag())) {
                        mSearchConditionMap.remove((String) nameSpinner.getTag());
                    }

                } else
                    // TODO: 2018/8/28
                    if ((familyNameList.get(nameSpinner.getSelectedItemPosition()).trim()).compareTo("A") >= 0
                            && familyNameList.get(nameSpinner.getSelectedItemPosition()).trim().compareTo("Z") <= 0) {
                        // 单独的拼音 大写字母,不处理
                        // 如果 选择了拼音首字母,重新定位到首位
                        nameSpinner.setSelection(0);
                    } else {
                        ((TextView) view).setTextColor(Color.RED);
                        mSearchConditionMap.put((String) nameSpinner.getTag(), familyNameList.get(nameSpinner.getSelectedItemPosition()));
                    }

                // TODO: 2018/8/13  对拼音的处理,数据库里增加一列,拼音
                // TODO: 2018/8/28  
                searchAndDisplayResultOnListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    // TODO: 2018/8/10  初始化 电话特征数字编辑框
    // TODO: 2018/8/28
    private void initPhones(final EditText phonesEditText) {
        phonesEditText.setHint("- 号码 -");
        phonesEditText.setTextSize(15.7245f);// 文字大小,试了多次
        phonesEditText.setPadding(8, 0, 8, 0);
        phonesEditText.setBackgroundColor(Color.WHITE);
        phonesEditText.setTextColor(Color.RED);
        phonesEditText.setCursorVisible(true);
        phonesEditText.addTextChangedListener(new TextWatcher() {
            String old = "";

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                old = s.toString();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                phonesEditText.clearFocus();
                phonesEditText.setCursorVisible(false);
                mSearchConditionMap.put((String) phonesEditText.getTag(), s.toString());
                searchAndDisplayResultOnListView();
            }
        });
        phonesEditText.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                phonesEditText.setText("");
                return true;
            }
        });
    }


    // TODO: 2018/8/11 在底部文本框显示要查询的条件
    // TODO: 2018/8/28
    private void searchAndDisplayResultOnListView() {
        String selection = "";
        ArrayList<String> selectionArgs = new ArrayList<>();
        Set<String> stringSet = mSearchConditionMap.keySet();
        int i = 0;
        for (String s : stringSet) {
            if (!TextUtils.isEmpty(mSearchConditionMap.get(s))) {
                // TODO: 2018/8/13 如果是模糊匹配电话号码
                if ("phones".equals(s)) {
                    selection += "phones LIKE ? AND ";
                    selectionArgs.add("%" + mSearchConditionMap.get(s).trim() + "%");
                } else if ("name".equals(s)) {
                    selection += "name LIKE ? AND ";
                    selectionArgs.add(mSearchConditionMap.get(s).trim() + "%");
                } else {
                    selection += s + " = ? AND ";
                    selectionArgs.add(mSearchConditionMap.get(s).trim());
                }
            }
        }
        String[] args = new String[selectionArgs.size()];
        if (TextUtils.isEmpty(selection)) {
            selection = null;
            args = null;
        } else {
            // 剔除最后的 'AND' 及 空格
            selection = selection.trim().substring(0, selection.trim().length() - 3);
            for (int i1 = 0; i1 < args.length; i1++) {
                args[i1] = selectionArgs.get(i1);
            }
        }
        final List<Folk> searchResultFolkListByCondition = mSqlMethod.findFolkListByCondition(selection, args);
        mPhonesListView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return searchResultFolkListByCondition == null ? 0 : searchResultFolkListByCondition.size();
            }

            @Override
            public Folk getItem(int position) {
                return searchResultFolkListByCondition == null ? null : searchResultFolkListByCondition.get(position);
            }

            @Override
            public long getItemId(int position) {
                return searchResultFolkListByCondition == null ? 0 : position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.each_body_detail, parent, false);
                    holder = new ViewHolder();
                    holder.personName = convertView.findViewById(R.id.item_personName);
                    holder.personMobilePhone = convertView.findViewById(R.id.item_personMobilePhone);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                holder.personName.setText(searchResultFolkListByCondition.get(position).getName());
                holder.personMobilePhone.setText(searchResultFolkListByCondition.get(position).getPhones());
                return convertView;
            }

            // TODO: 2018/8/11
            class ViewHolder {
                TextView personName;
                TextView personMobilePhone;
            }
        });
    }


    // TODO: 2018/8/10 初始化所需要的数据
    // TODO: 2018/8/28
    private void initData() {
        mSqlMethod = new SqlMethod(this);
        //    mFolkList = mSqlMethod.findFolkList();
        mFolkCursor = mSqlMethod.findFolkCursor();
        mSearchConditionMap = new HashMap<>();
    }


    // TODO: 2018/8/10 初始化视图
    // TODO: 2018/8/28
    private void initView() {
        mPhonesEditText = findViewById(R.id.phones_edittext__activity_phone_list);
        mNameSpinner = findViewById(R.id.name_spinner__activity_phone_list);
        mUnitSpinner = findViewById(R.id.unit_spinner__activity_phone_list);
        mDeptSpinner = findViewById(R.id.dept_spinner__activity_phone_list);
        mRankSpinner = findViewById(R.id.rank_spinner__activity_phone_list);
        mOfficeSpinner = findViewById(R.id.office_spinner__activity_phone_list);
        mRoomNumberSpinner = findViewById(R.id.roomNumber_spinner__activity_phone_list);
        mInPhonesSpinner = findViewById(R.id.inPhones_spinner__activity_phone_list);
        mOutPhonesSpinner = findViewById(R.id.outPhones_spinner__activity_phone_list);
        mNickNameSpinner = findViewById(R.id.nickName_spinner__activity_phone_list);
        mAddressSpinner = findViewById(R.id.address_spinner__activity_phone_list);
        mInGroupSpinner = findViewById(R.id.inGroup_spinner__activity_phone_list);
        mLastCallsSpinner = findViewById(R.id.lastCalls_spinner__activity_phone_list);
        mPhonesListView = findViewById(R.id.listview_phones___activity_phone_list);
        mCombineConditionTextView = findViewById(R.id.textview_search_condition__activity_phone_list);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //Activity生命周期中，onStart, onResume, onCreate都不是真正visible的时间点，
        // 真正的visible时间点是onWindowFocusChanged()函数被执行时
        //显示时,不显示光标与焦点,仅好看一些,无用的
        mPhonesEditText.clearFocus();
        mPhonesEditText.setCursorVisible(false);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.system_option_menu_layout, menu);
//        View read_contact = findViewById(R.id.read_contact_from_mobile__system_option_menu_layout);
//        View write_contact = findViewById(R.id.write_contact_from_mobile__system_option_menu_layout);
//        View new_person = findViewById(R.id.new_person__system_option_menu_layout);
//        View delete_person = findViewById(R.id.delete_person__system_option_menu_layout);
//        View batch_insert_new_person = findViewById(R.id.batch_insert_new_person_via_text_file__system_option_menu_layout);
//        View insert_new_person_by_ocr = findViewById(R.id.insert_new_person_by_ocr__system_option_menu_layout);
//

        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {


            case R.id.read_contact_from_mobile__system_option_menu_layout:
                // TODO: 2018/8/14  读取系统通讯录
                Intent read_contact_from_mobile_intent = new Intent(ShowContactPhoneActivity.this, FindSystemContactThenSaveToThisAppActivity.class);
                Bundle read_contact_from_mobile_bundle = getBundleArgs();
                read_contact_from_mobile_intent.putExtras(read_contact_from_mobile_bundle);
                startActivity(read_contact_from_mobile_intent);
                break;

            case R.id.write_contact_from_mobile__system_option_menu_layout:
                // TODO: 2018/8/14  保存到系统通讯录

                break;

            case R.id.new_person__system_option_menu_layout:
                // TODO: 2018/8/14  新建联系人
                Intent new_person_intent = new Intent(ShowContactPhoneActivity.this, NewPersonActivity.class);
                Bundle new_person_bundle = getBundleArgs();
                new_person_intent.putExtras(new_person_bundle);
                startActivity(new_person_intent);
                //          ShowContactPhoneActivity.this.finish();
                break;

            case R.id.modify_person__system_option_menu_layout:
                // TODO: 2018/8/14  修改联系人

                break;

            case R.id.delete_person__system_option_menu_layout:
                // TODO: 2018/8/14  删除联系人

                break;

            case R.id.batch_insert_new_person_via_text_file__system_option_menu_layout:
                // TODO: 2018/8/14  文件导入联系人

                break;

            case R.id.insert_new_person_by_ocr__system_option_menu_layout:
                // TODO: 2018/8/14  扫描名片导入

                break;

            default:


        }

        return super.onOptionsItemSelected(item);
    }

    @NonNull
    private Bundle getBundleArgs() {
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("unit", mUnitList);
        bundle.putStringArrayList("dept", mDeptList);
        bundle.putStringArrayList("rank", mRankList);
        bundle.putStringArrayList("office", mOfficeList);
        bundle.putStringArrayList("roomNumber", mRoomNumberList);
        bundle.putStringArrayList("inPhones", mInPhonesList);
        bundle.putStringArrayList("outPhones", mOutPhonesList);
        bundle.putStringArrayList("nickName", mNickNameList);
        bundle.putStringArrayList("address", mAddressList);
        bundle.putStringArrayList("inGroup", mInGroupList);
        return bundle;
    }
}
